/**
 * 
 */
package vn.lumi.smarthome.network;

import vn.lumi.smarthome.io.database.TBL_Schedule;
import vn.lumi.smarthome.io.model.Schedule;
import android.content.ContentValues;
import android.content.Context;
import android.util.Log;

/**
 * @author Chu Tuan Anh
 *
 */
public class UpdateScheduleState extends HCMsg{

	//constant
	String TAG = "UpdateScheduleState";
	public static final int LENGTH = 4;
	
	//variables
	private int userId = 0;
	private int scheduleId = 0;
	private int scheduleState = Schedule.SCHEDULE_STATE_OFF;

	private boolean isCorrectFormat = false;
	
	//byte positions
	private static final int userIdPos = 1;
	
	/**
	 * @param cmd_id
	 * @param Msg_id
	 * @param len
	 */
	public UpdateScheduleState(int userId) {
		super(NetMessage.CMD_HC_UPDATE_SCHEDULE_STATE, 0, LENGTH);
		// TODO Auto-generated constructor stub
		this.userId = userId;
	}


	/* (non-Javadoc)
	 * @see vn.lumi.smarthome.network.HCMsg#parseMessage(byte[], int)
	 */
	@Override
	public void parseMessage(byte[] input, int length) {
		// TODO Auto-generated method stub
		isCorrectFormat = isCorrectFormat(input,length);
		if(isCorrectFormat == false) return;
		
		this.scheduleId = Byte2Unsigned(input[2]);
		this.scheduleState = Byte2Unsigned(input[3]);
	}

	/* (non-Javadoc)
	 * @see vn.lumi.smarthome.network.HCMsg#doWhenReceived(android.content.Context)
	 */
	@Override
	public void doWhenReceived(Context context) {
		// TODO Auto-generated method stub
		if(isCorrectFormat == false) return;
		//update state of schedule 
		String selection = new String(TBL_Schedule._ID+"=?");
		String[] selectionArgs = new String[]{this.scheduleId+""};
		ContentValues values = new ContentValues();
		values.put(TBL_Schedule.STATE, this.scheduleState);
		context.getContentResolver().update(TBL_Schedule.CONTENT_URI_SCHEDULE, values, selection, selectionArgs);
		        
        Log.d(TAG,"schedule_id="+this.scheduleId+" state="+this.scheduleState);;
	}
	
	@Override
	public boolean isCorrectFormat(byte[] input, int length){
		boolean result = false;
		if(super.isCorrectFormat(input, length) == false)
			result =  false;
		else{
			if(this.userId == Byte2Unsigned(input[userIdPos])) result =  true;
			else result =  false;
		}
		return result;
	}

}
